/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <FreeRTOS.h>
#include <queue.h>
#include <stdio.h>
#include <task.h>
#include <tvm_runtime.h>

#include "ethosu_mod.h"
#include "uart.h"

// Header files generated by convert_image.py and convert_labels.py
#include "inputs.h"
#include "labels.h"
#include "outputs.h"

static void prvInferenceTask(void* pvParameters);
static void prvDataCollectionTask(void* pvParameters);

#define mainQUEUE_INFERENCE_TASK_PRIORITY (tskIDLE_PRIORITY + 3)
#define mainQUEUE_INFERENCE_TASK_STACK_SIZE 4096
#define mainQUEUE_DATA_TASK_PRIORITY (tskIDLE_PRIORITY + 2)
#define mainQUEUE_DATA_TASK_STACK_SIZE configMINIMAL_STACK_SIZE
#define mainQUEUE_LENGTH (1)
#define mainQUEUE_SEND_FREQUENCY_MS (100 / portTICK_PERIOD_MS)

/* The queue used to pass data to run through our model */
static QueueHandle_t xQueue = NULL;

int main(void) {
  // Platform UART
  uart_init();
  // NPU
  EthosuInit();

  // Queue for inferences
  xQueue = xQueueCreate(mainQUEUE_LENGTH, sizeof(uint8_t*));

  if (xQueue != NULL) {
    // Inference task
    xTaskCreate(prvInferenceTask, "Inference", mainQUEUE_INFERENCE_TASK_STACK_SIZE, NULL,
                mainQUEUE_INFERENCE_TASK_PRIORITY, NULL);

    // Data collector task
    xTaskCreate(prvDataCollectionTask, "Data", mainQUEUE_DATA_TASK_STACK_SIZE, NULL,
                mainQUEUE_DATA_TASK_PRIORITY, NULL);

    // Start the task scheduling
    vTaskStartScheduler();
  }

  // The task scheduler should take over before this is reached
  printf("Unreachable code reached!\n");
}

/*
 * This task emulates collection of data and sending it to another inference task
 * for processing
 */
static void prvDataCollectionTask(void* pvParameters) {
  // Unused
  (void)pvParameters;

  // Working
  vTaskDelay(mainQUEUE_SEND_FREQUENCY_MS);

  // Construct pointer to copy to queue
  uint8_t** pucInputData = &input;
  xQueueSend(xQueue, &pucInputData, 0U);
}

/*
 * This task emulates the inference of data sent by the collector task
 */
static void prvInferenceTask(void* pvParameters) {
  uint8_t* pucReceivedData;

  // Unused
  (void)pvParameters;

  // Wait for data collection
  xQueueReceive(xQueue, &pucReceivedData, portMAX_DELAY);

  // Print output of inference and exit task
  printf("Running inference\n");
  struct tvmgen_default_inputs xInputs = {
      .tfl_quantize = pucReceivedData,
  };
  struct tvmgen_default_outputs xOutputs = {
      .MobilenetV2_Predictions_Reshape_11 = output,
  };
  struct ethosu_driver* xDriver = ethosu_reserve_driver();
  struct tvmgen_default_devices xDevices = {
      .ethos_u = xDriver,
  };
  tvmgen_default_run(&xInputs, &xOutputs, &xDevices);
  ethosu_release_driver(xDriver);

  // Calculate index of max value
  int8_t ucMaxValue = -128;
  int32_t lMaxIndex = -1;
  for (unsigned int i = 0; i < output_len; ++i) {
    if (output[i] > ucMaxValue) {
      ucMaxValue = output[i];
      lMaxIndex = i;
    }
  }
  printf("The image has been classified as '%s'\n", labels[lMaxIndex]);

  // The FVP will shut down when it receives "EXITTHESIM" on the UART
  printf("EXITTHESIM\n");
}
